package com.spark.lola.rpc;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.spark.lola.constant.SupOrderStatus;
import com.spark.lola.feign.LogisticsFeignService;
import com.spark.lola.feign.PurReportFeignService;
import com.spark.lola.feign.SupFeignService;
import com.spark.lola.logistics.entity.LocationInfo;
import com.spark.lola.mapper.statistics.StatisticsDestinationMapper;
import com.spark.lola.mapper.statistics.StatisticsPurchaseMapper;
import com.spark.lola.mapper.statistics.StatisticsSalesmanMapper;
import com.spark.lola.mapper.statistics.StatisticsSupplierMapper;
import com.spark.lola.statistics.entity.StatisticsDestination;
import com.spark.lola.statistics.entity.StatisticsPurchase;
import com.spark.lola.statistics.entity.StatisticsSalesman;
import com.spark.lola.statistics.entity.StatisticsSupplier;
import com.spark.lola.statistics.vo.PurchaseStatisticsVo;
import com.spark.lola.statistics.vo.PurchaseWorkVo;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.common.util.TimeUtil;
import com.spark.lola.support.mybatis.entity.PageParam;
import com.spark.lola.support.mybatis.entity.QueryParam;
import com.spark.lola.support.mybatis.entity.ShiroQueryParam;
import com.spark.lola.support.wms.configuration.WmsProperties;
import com.spark.lola.support.wms.constant.StatisticsGroupType;
import com.spark.lola.support.wms.constant.SupOrderByType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 供应商报表
 * @Author: DengYeJun
 * @Date: 2020/5/19 19:26
 */
@RestController
@RequestMapping(value = "/rpc/pur", produces = "application/json;charset=UTF-8")
public class PurReportFeignServiceImpl implements PurReportFeignService {
    @Autowired
    private StatisticsPurchaseMapper purchaseMapper;
    @Autowired
    private StatisticsSupplierMapper supplierMapper;
    @Autowired
    private StatisticsSalesmanMapper salesmanMapper;
    @Autowired
    private StatisticsDestinationMapper destinationMapper;
    @Autowired
    private WmsProperties wmsProperties;
    @Autowired
    private SupFeignService supFeignService;
    @Autowired
    private LogisticsFeignService logisticsFeignService;


    @Override
    @RequestMapping(value = "/statistics/employee/{start}/{end}",method = RequestMethod.POST)
    public PurchaseStatisticsVo employeeStatistics(@RequestBody ShiroUser shiroUser,@PathVariable String start,@PathVariable String end) {
        PurchaseStatisticsVo vo = new PurchaseStatisticsVo();
        Long salesmanId = 0L;
        List<String> controlUsers = new ArrayList<>();
        int type = SupOrderByType.NORMAL;
        int factoryCount=-1;
        if (wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            // 是否业务员
            salesmanId = shiroUser.getId();
            type = SupOrderByType.SALESMAN;
            StatisticsSalesman statistics = salesmanMapper.statistics(salesmanId, start, end);
            BeanUtils.copyProperties(statistics, vo);
        }
        else if(wmsProperties.getPurchase().getDutyId().get(0).equals(shiroUser.getDutyId())
                 ){
            // 业务主管
            type = SupOrderByType.LEADER;
            factoryCount = dealStatisticByBizLeader(controlUsers,shiroUser,start,end,vo);
        }
        else if(wmsProperties.getPurchase().getDutyId().get(3).equals(shiroUser.getDutyId())){
            // 财务
            type = SupOrderByType.LEADER;
            factoryCount = dealStatisticByFin(controlUsers,shiroUser,start,end,vo);
        }
        else if(wmsProperties.getPurchase().getDutyId().get(4).equals(shiroUser.getDutyId())){
            // 出纳
            type = SupOrderByType.CASHIER;
            salesmanId = shiroUser.getId();
            factoryCount = dealStatisticByCashier(controlUsers,shiroUser,start,end,vo);
        }
        else if (!StringUtils.isEmpty(shiroUser.getControlUsers())
                && shiroUser.getDeptId().equals(wmsProperties.getPurchase().getDeptId())
        ) {
            controlUsers = Arrays.asList( shiroUser.getControlUsers().split(","));
            type = SupOrderByType.REGULATOR;
            StatisticsSalesman statistics = salesmanMapper.statisticsBySalesmans(controlUsers.toArray(), start, end);
            BeanUtils.copyProperties(statistics, vo);
        } else {
            StatisticsPurchase statistics = purchaseMapper.statistics(start, end);
            BeanUtils.copyProperties(statistics, vo);
        }

        // 绑定待结算金额
        vo.setWaitPayment(supFeignService.waitingPayment(type, salesmanId, controlUsers,start,end));
        // 绑定供应商数量
        vo.setSuplierCount(supFeignService.supplierCount(salesmanId));
        if(factoryCount==-1){
            factoryCount = logisticsFeignService.getCompanySize();
        }
        vo.setFactoryCount(factoryCount);
        if (salesmanId.equals(0L)) {
            // 绑定业务员数量
            vo.setSalesmanCount(supFeignService.salesmanCount());
        }
        return vo;
    }

    /**
     * 处理 业务主管
     */
    private int dealStatisticByBizLeader(List<String> controlUsers, ShiroUser shiroUser,String start ,String end,PurchaseStatisticsVo vo){
        List<Long> ids = logisticsFeignService.getIdsByLeaderId(shiroUser.getId());
        for(Long id :ids){
            controlUsers.add(id.toString());
        }
        StatisticsDestination statistics = destinationMapper.statisticsByIds(ids,start,end);
        BeanUtils.copyProperties(statistics, vo);
        return ids.size();
    }

    /**
     * 处理 财务
     */
    private int dealStatisticByFin(List<String> controlUsers, ShiroUser shiroUser,String start ,String end,PurchaseStatisticsVo vo){
        List<Long> ids = logisticsFeignService.getIdsByPurchaseId(shiroUser.getId());
        for(Long id :ids){
            controlUsers.add(id.toString());
        }
        StatisticsDestination statistics = destinationMapper.statisticsByIds(ids,start,end);
        BeanUtils.copyProperties(statistics, vo);
        return ids.size();
    }

    /**
     * 处理 出纳
     */
    private int dealStatisticByCashier(List<String> controlUsers, ShiroUser shiroUser,String start ,String end,PurchaseStatisticsVo vo){
        List<Long> ids = logisticsFeignService.getIdsByCashier(shiroUser.getId());
        for(Long id :ids){
            controlUsers.add(id.toString());
        }
        StatisticsDestination statistics = destinationMapper.statisticsByIds(ids,start,end);
        BeanUtils.copyProperties(statistics, vo);
        return ids.size();
    }

    @Override
    @RequestMapping(value = "/statistics/supplier",method = RequestMethod.POST)
    public PurchaseStatisticsVo supplierStatistics(@RequestParam("supplierId") Long supplierId,@RequestParam("start") String start,@RequestParam("end") String end) {
        StatisticsSupplier statistics = supplierMapper.statistics(supplierId, start, end);
        PurchaseStatisticsVo vo = new PurchaseStatisticsVo();
        BeanUtils.copyProperties(statistics, vo);
        // 绑定待结算金额
        vo.setWaitPayment(supFeignService.supplierWaitingPayment(supplierId));
        return vo;
    }

    @RequestMapping(value = "/statistics/destination",method = RequestMethod.POST)
    @Override
    public StatisticsDestination destinationStatistics(@RequestParam("destinationId") Long destinationId,@RequestParam("start") String start,@RequestParam("end") String end) {
        return destinationMapper.statistics(destinationId, start, end);
    }


    @Override
    @RequestMapping(value = "/work/employee",method = RequestMethod.POST)
    public PurchaseWorkVo employeeWork(@RequestBody ShiroUser shiroUser) {
        Integer type = SupOrderByType.NORMAL;
        Long byId = 0L;
        List<String> salesmanIds =new ArrayList<>();
        salesmanIds.add("0");
        if (wmsProperties.getPurchase().getDutyId().get(1).equals(shiroUser.getDutyId())) {
            // 业务员
            type = SupOrderByType.SALESMAN;
            byId = shiroUser.getId();
        }
        if (wmsProperties.getPurchase().getDutyId().get(2).equals(shiroUser.getDutyId())) {
            // 接货员
            type = SupOrderByType.CONSIGNEE;
            byId = shiroUser.getId();
        }
        if (wmsProperties.getPurchase().getDutyId().get(4).equals(shiroUser.getDutyId())) {
            // 出纳
            type = SupOrderByType.CASHIER;
            byId = shiroUser.getId();
        }
        if (wmsProperties.getPurchase().getDutyId().get(0).equals(shiroUser.getDutyId())) {
            // 业务主管
            type = SupOrderByType.LEADER;
            // 纸厂
            List<Long> desctIds = logisticsFeignService.getIdsByLeaderId(shiroUser.getId());
            if(!CollectionUtils.isEmpty(desctIds)) {
                for (Long id : desctIds) {
                    salesmanIds.add(id.toString());
                }
            }
        }
        if (wmsProperties.getPurchase().getDutyId().get(3).equals(shiroUser.getDutyId())) {
            // 财务
            type = SupOrderByType.LEADER;
            // 纸厂
            List<Long> desctIds = logisticsFeignService.getIdsByPurchaseId(shiroUser.getId());
            if(!CollectionUtils.isEmpty(desctIds)) {
                for (Long id : desctIds) {
                    salesmanIds.add(id.toString());
                }
            }
        }

        if(type.equals(SupOrderByType.NORMAL)
                && wmsProperties.getPurchase().getDeptId().equals(shiroUser.getDeptId())
                && !StringUtils.isEmpty(shiroUser.getControlUsers())
        ){
            // 采购部
            type = SupOrderByType.REGULATOR;
            salesmanIds = Arrays.asList(shiroUser.getControlUsers().split(","));
        }
        return dealWork(type,byId,salesmanIds);
    }

    @Override
    @RequestMapping(value = "/work/supplier",method = RequestMethod.POST)
    public PurchaseWorkVo supplierWork(Long supplierId) {
        return dealWork(SupOrderByType.SUPPLIER,supplierId,new ArrayList<>());
    }

    private PurchaseWorkVo dealWork(Integer type,Long byId,List<String> salesmanIds){
        Map<Integer, Integer> orderCount = supFeignService.orderCountByStatus(type,byId,salesmanIds);
        PurchaseWorkVo vo = new PurchaseWorkVo();
        vo.setWaiting(orderCount.get(SupOrderStatus.WAIT));
        vo.setWaitEceiving(orderCount.get(SupOrderStatus.WAIT_ECEIVING));
        vo.setWaitPricing(orderCount.get(SupOrderStatus.WAIT_PRICING));
        vo.setWaitAdjust(orderCount.get(SupOrderStatus.WAIT_ADJUST));
        vo.setWaitPayment(orderCount.get(SupOrderStatus.WAIT_PAYMENT));
        return vo;
    }

    @Override
    @RequestMapping(value = "/report/purchase/day",method = RequestMethod.POST)
    public Page<StatisticsPurchase> dayPurchaseReport(@RequestBody ShiroQueryParam<StatisticsPurchase> queryBean) {
        PageParam<StatisticsPurchase> pageParam = queryBean.getQueryParam().toPageParam();
        return purchaseMapper.page(pageParam.getPage(), StatisticsGroupType.DAY, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/purchase/month",method = RequestMethod.POST)
    public Page<StatisticsPurchase> monthPurchaseReport(@RequestBody ShiroQueryParam<StatisticsPurchase> queryBean) {
        PageParam<StatisticsPurchase> pageParam = queryBean.getQueryParam().toPageParam();
        return purchaseMapper.page(pageParam.getPage(), StatisticsGroupType.MONTH, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/purchase/year",method = RequestMethod.POST)
    public Page<StatisticsPurchase> yearPurchaseReport(@RequestBody ShiroQueryParam<StatisticsPurchase> queryBean) {
        PageParam<StatisticsPurchase> pageParam = queryBean.getQueryParam().toPageParam();
        return purchaseMapper.page(pageParam.getPage(), StatisticsGroupType.YEAR, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/salesman/day",method = RequestMethod.POST)
    public Page<StatisticsSalesman> daySalesmanReport(@RequestBody ShiroQueryParam<StatisticsSalesman> queryBean) {
        PageParam<StatisticsSalesman> pageParam = queryBean.getQueryParam().toPageParam();
        return salesmanMapper.page(pageParam.getPage(), StatisticsGroupType.DAY, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/salesman/month",method = RequestMethod.POST)
    public Page<StatisticsSalesman> monthSalesmanReport(@RequestBody ShiroQueryParam<StatisticsSalesman> queryBean) {
        PageParam<StatisticsSalesman> pageParam = queryBean.getQueryParam().toPageParam();
        return salesmanMapper.page(pageParam.getPage(), StatisticsGroupType.MONTH, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/salesman/year",method = RequestMethod.POST)
    public Page<StatisticsSalesman> yearSalesmanReport(@RequestBody ShiroQueryParam<StatisticsSalesman> queryBean) {
        PageParam<StatisticsSalesman> pageParam = queryBean.getQueryParam().toPageParam();
        return salesmanMapper.page(pageParam.getPage(), StatisticsGroupType.YEAR, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/supplier/day/{supplierId}",method = RequestMethod.POST)
    public Page<StatisticsSupplier> daySupplierReport(@RequestBody QueryParam<StatisticsSupplier> queryBean, @PathVariable Long supplierId) {
        PageParam<StatisticsSupplier> pageParam = queryBean.toPageParam();
        // TODO 供应商
        return supplierMapper.page(pageParam.getPage(), StatisticsGroupType.DAY, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/supplier/month",method = RequestMethod.POST)
    public Page<StatisticsSupplier> monthSupplierReport(@RequestBody QueryParam<StatisticsSupplier> queryBean, @PathVariable Long supplierId) {
        PageParam<StatisticsSupplier> pageParam = queryBean.toPageParam();
        return supplierMapper.page(pageParam.getPage(), StatisticsGroupType.MONTH, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/supplier/year",method = RequestMethod.POST)
    public Page<StatisticsSupplier> yearSupplierReport(@RequestBody QueryParam<StatisticsSupplier> queryBean, @PathVariable Long supplierId) {
        PageParam<StatisticsSupplier> pageParam = queryBean.toPageParam();
        return supplierMapper.page(pageParam.getPage(), StatisticsGroupType.YEAR, pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/supplier/sum",method = RequestMethod.POST)
    public Page<StatisticsDestination> sumDestinationReport(@RequestBody QueryParam<StatisticsDestination> queryBean) {
        PageParam<StatisticsDestination> pageParam = queryBean.toPageParam();
        return destinationMapper.page(pageParam.getPage(),StatisticsGroupType.SLEF,pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/destination/day/{destinationId}",method = RequestMethod.POST)
    public Page<StatisticsDestination> dayDestinationReport(@RequestBody QueryParam<StatisticsDestination> queryBean,
                                                            @PathVariable Long destinationId) {
        PageParam<StatisticsDestination> pageParam = queryBean.toPageParam();
        return destinationMapper.page(pageParam.getPage(),StatisticsGroupType.DAY,pageParam.getEntityWrapper());
    }



    @Override
    @RequestMapping(value = "/report/destination/month/{destinationId}",method = RequestMethod.POST)
    public Page<StatisticsDestination> monthDestinationReport(@RequestBody QueryParam<StatisticsDestination> queryBean,
                                                              @PathVariable Long destinationId) {
        PageParam<StatisticsDestination> pageParam = queryBean.toPageParam();
        return destinationMapper.page(pageParam.getPage(),StatisticsGroupType.MONTH,pageParam.getEntityWrapper());
    }

    @Override
    @RequestMapping(value = "/report/destination/year/{destinationId}",method = RequestMethod.POST)
    public Page<StatisticsDestination> yearDestinationReport(@RequestBody QueryParam<StatisticsDestination> queryBean,
                                                             @PathVariable Long destinationId) {
        PageParam<StatisticsDestination> pageParam = queryBean.toPageParam();
        return destinationMapper.page(pageParam.getPage(), StatisticsGroupType.YEAR, pageParam.getEntityWrapper());
    }

}
